package com.eascs.admin.o2o.detail.controller;
//import java.text.DecimalFormat;
//import java.text.Format;
//import java.util.List;

import java.math.BigDecimal;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
//import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.detail.service.LoanDetailService;
import com.eascs.admin.o2o.internal.entity.LoanapplyExpand;
import com.eascs.admin.o2o.internal.form.UpdateLoanapplyExpand;
import com.eascs.admin.o2o.internal.service.LoanapplyExpandService;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oChargeSituationService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.oper.entity.O2oOperationUploanlog;
import com.eascs.admin.o2o.oper.service.IO2oOperationUploanlogService;
import com.eascs.afterloan.entity.AdvancedPayment;
import com.eascs.afterloan.service.AdvanceSettleService;
import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
//import com.eascs.common.util.StringUtil;
//import com.eascs.crm.common.entity.CustomerShopInfoEntity;
import com.eascs.crm.nsEditDetail.entity.CustomerShopInfoEntity;
//import com.eascs.crm.common.service.ICustomerInfoService;
//import com.eascs.crm.common.vo.QueryCustomerVO;
import com.eascs.crm.nsEditDetail.service.CustomerShopInfoService;
import com.eascs.file.FileTypeConstants;
import com.eascs.loan.entity.O2oBankLoanData;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.page.PaginationInfo;
//import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.form.MQZBSBYHFrom;
/**
 * 贷款详情 输出页面 
 * @author ycz
 *
 */
@Controller
@RequestMapping("/loanDetail")
public class LoanDetailRestController extends BaseRestController {
	private static Logger logger = LoggerFactory.getLogger(LoanDetailRestController.class);
	@Autowired
	private O2oLoanapplyService o2oloanapplyService;
	@Autowired
	private LoanDetailService loanDetailService;
	@Autowired
	private O2oLoanService o2oLoanService;
//	@Reference
//	ICustomerInfoService customerInfoService;
	@Autowired
	private LoanapplyExpandService loanapplyExpandService;
	@Autowired
	AdvanceSettleService advanceSettleService;
	@Autowired
	CustomerShopInfoService shopInfoService;
	
	@Reference
	IO2oOperationUploanlogService io2oOperationUploanlogService;
	
	@Autowired
	private O2oChargeSituationService o2oChargeSituationService;
	

	/**
	 * 银行卡信息详情
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/queryBank")
	public HtmlRestResult queryBankInfo(String loanapplyNo,String type){
		O2oLoanapplyEntity loanapply=o2oloanapplyService.findById(loanapplyNo);
		O2oLoanUserEntity loanUser = o2oloanapplyService.findLoanUserEntity(loanapply.getLoanapplyNo(), loanapply.getLoanId());
		ViewContext.put("type", type);
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("loanapplyEntity", loanapply);
		return HtmlRestResult.html("detail/bankInfo");
	}
	/**
	 * 编辑银行卡信息
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/editBank")
	public HtmlRestResult editBankInfo(String loanapplyNo){
		O2oLoanapplyEntity loanapply=o2oloanapplyService.findById(loanapplyNo);
		O2oLoanUserEntity loanUser = o2oloanapplyService.findLoanUserEntity(loanapply.getLoanapplyNo(), loanapply.getLoanId());
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("loanapplyEntity", loanapply);
		return HtmlRestResult.popHtmlFragment("detail/editBank");
	}
	/**
	 * 重新拉取合同
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/pushContract")
	public BaseRestResult<String> delContract(String loanapplyNo){
		boolean flag=loanDetailService.delContract(loanapplyNo);
		if(flag){
			return BaseRestResult.info("操作成功").andRefresh();
		}else{
			return BaseRestResult.warn("操作失败");
		}
	}
	
	/**
	 * 编辑银行卡信息
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/editShop")
	public BaseRestResult<String> editShop(CustomerShopInfoEntity mainShop){
//		QueryCustomerVO vo=new QueryCustomerVO();
//		vo.setCustomer_shop_id(mainShop.getCustomerShopId());
//		CustomerShopInfoEntity entity=customerInfoService.getCustomerShopInfoEntity(vo);
		CustomerShopInfoEntity shop = shopInfoService.queryById(mainShop.getCustomerShopId());//门店信息
		
		shop.setControllername(mainShop.getControllername());
		shop.setControllerIdnum(mainShop.getControllerIdnum());
		shop.setControllerMobile(mainShop.getControllerMobile());
		//boolean flag=customerInfoService.updateStore(shop);
		boolean flag=shopInfoService.update(shop);
		if(flag){
			return BaseRestResult.info("操作成功").andRefresh();
		}else{
			return BaseRestResult.warn("操作失败");
		}
	}
	/**
	 * 详情页面修改内审汇率
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/editInternal")
	public HtmlRestResult editInternal(String loanapplyNo){
		O2oLoanapplyEntity loan = o2oloanapplyService.findById(loanapplyNo);
		logger.info("详情页修改内审表单:[{}],billCode:[{}]", loanapplyNo,loan.getBillCode());
		LoanapplyExpand expand = loanapplyExpandService.queryLoanapplyNo(loanapplyNo);
		loan.setPaymentType("LDZJ");
		ViewContext.put("loan", loan);
		ViewContext.put("expand", expand);
		if(StatusContexts.LOAN_TYPE_EA.equals(loan.getLoanType())){
			return HtmlRestResult.html("workflowcheck/ns_ea");
		}else if(StatusContexts.LOAN_TYPE_FQ.equals(loan.getLoanType())){
			return HtmlRestResult.html("workflowcheck/ns_fq");
		}else{
			queryDataListNS(loanapplyNo, FileTypeConstants.DALIST_TYPE_NSFJ,null);
			queryDataList(loanapplyNo, FileTypeConstants.DALIST_TYPE_DCWD, null);
			return HtmlRestResult.popHtmlFragment("workflowcheck/ns_zbfs");
		}
	}
	/**
	 * 修改收费金额页面跳转
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/editExpand")
	public HtmlRestResult editExpand(String loanapplyNo){
		LoanapplyExpand loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(loanapplyNo);
		logger.info("详情页修改收费金额ID:[{}],billCode:[{}]", loanapplyNo,loanapplyExpand.getBillCode());
		ViewContext.put("loanapplyExpand", loanapplyExpand);
		return HtmlRestResult.popHtmlFragment("detail/editExpand");
	}
	
	
	/**
	 * 调账，扣费，退款
	 * 
	 * 
	 * @return
	 */
	@RequestMapping("/dkdzh")
	public BaseRestResult<String> dkdzh(String loanapplyNo,String type) {
		logger.info("访问显示扣费界面接口开始");
		logger.info("查询贷款保证金开始");
		
		LoanapplyExpand loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(loanapplyNo);
		
		if(loanapplyExpand==null){
			return BaseRestResult.warn("未找到收费数据");
		}
		
		LoanapplyExpand expand = o2oChargeSituationService.queryExpandByLoanapplyNo(loanapplyNo);
		logger.info("查询贷款保证金信息:{}", expand);
		BigDecimal freezeBalance = o2oChargeSituationService.getFreezeBalance(loanapplyNo);
		ViewContext.put("amountAvailable", freezeBalance);
		ViewContext.put("loanapplyNo", loanapplyNo);
		ViewContext.put("expand", expand);
		ViewContext.put("type", type);
		return HtmlRestResult.popHtmlFragment("detail/charge_situation");
	}
	
	
	/**
	 * 修改费用 保证金、管理费和风险补偿金
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/updateExpand")
	public BaseRestResult<String> updateExpand(UpdateLoanapplyExpand updateLoanapplyExpand){
		
		LoanapplyExpand expand = loanapplyExpandService.queryLoanapplyNo(updateLoanapplyExpand.getLoanapplyNo());
		logger.info("修改收费金额:billCode:[{}],保证金：[{}],管理费：[{}],风险补偿金：[{}]", expand.getBillCode(),expand.getRecDeposite(),expand.getRecManger(),expand.getRecRisk());
		expand.setRecDeposite(updateLoanapplyExpand.getRecDeposite());
		expand.setRecManger(updateLoanapplyExpand.getRecManger());
		expand.setRecRisk(updateLoanapplyExpand.getRecRisk());
		loanapplyExpandService.updateById(expand);
		O2oOperationUploanlog uploanlog = new O2oOperationUploanlog();
		uploanlog.setBillCode(expand.getBillCode());
		uploanlog.setLoanapplyNo(expand.getLoanapply_no());
		uploanlog.setUpRemart(updateLoanapplyExpand.getUpRemart());
		uploanlog.setUpTime(new Date());
		uploanlog.setUpUserName(UserHolder.getUser().getCname());
		uploanlog.setUpUserNo(UserHolder.getUser().getNo());
		io2oOperationUploanlogService.insert(uploanlog);
		return BaseRestResult.warn("修改成功");
	}
	/**
	 * 附件
	 * @param loanapplyNo
	 * @param code
	 * @param type
	 */
	public void queryDataList(String loanapplyNo, String code,String type) {
		PageResult<Object[]> pageResult = o2oloanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		AjaxConfirmButton[] dealButton=null;
		if(type==null){
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		} else if(type.equals("NS_XDJL")){
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		}else if(type.equals("TQHK")){
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		}
		paginationInfo.setMoreButtons(dealButton);
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResult", paginationInfo);// 个人附件
	}
	/**
	 * 附件
	 * @param loanapplyNo
	 * @param code
	 * @param type
	 */
	public void queryDataListNS(String loanapplyNo, String code,String type) {
		PageResult<Object[]> pageResult = o2oloanapplyService.findO2oDataListEntityById(loanapplyNo, "'" + code + "'");
		String titles[] = { "附件类型", "文件名", "提交人", "提交时间", "更新时间" };
		Button[] titleButtons = new Button[] { null,
				ButtonHelper.createOpenButton(null, "/file/download?datalistno=") };
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles);
		AjaxConfirmButton[] dealButton=null;
		if(type==null){
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		} else if(type.equals("NS_XDJL")){
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		}else if(type.equals("TQHK")){
			dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除 ", "/loanrest/delete/") };
		}
		paginationInfo.setMoreButtons(dealButton);
		paginationInfo.setTitleButtons(titleButtons);
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		paginationInfo.setBuildRowNumber(true);
		ViewContext.put("pageResultNS", paginationInfo);// 个人附件
	}
	@RequestMapping("/advancedPay")
	public HtmlRestResult advancedPay(String loanapplyNo){
		O2oLoanapplyEntity loanapply=o2oloanapplyService.findById(loanapplyNo);
		O2oLoanUserEntity loanUser = o2oloanapplyService.findLoanUserEntity(loanapply.getLoanapplyNo(), loanapply.getLoanId());
		O2oBankLoanData bankData = o2oLoanService.queryBillCode(loanapply.getBillCode());
		AdvancedPayment advanceSettleForm	=advanceSettleService.queryById(loanapplyNo);
		ViewContext.put("loanUser", loanUser);
		ViewContext.put("loanapply", loanapply);
		ViewContext.put("bankData", bankData);
		ViewContext.put("advanceSettleForm", advanceSettleForm);
		return HtmlRestResult.popHtmlFragment("detail/advancedPay");
	}
	
	
	/**
	 * @Title: queryFile
	 * @Description: 局部加载附件文件
	 * @author 张庆奇
	 * @param parameter
	 * @return
	 * @return HtmlRestResult
	 * @throws
	 * @date 2017年2月14日 下午3:56:28
	 */
	@RequestMapping("/loadfile")
	public HtmlRestResult queryFile(String parameter) {
		queryDataList(parameter, FileTypeConstants.DALIST_TYPE_TQHK,null);
		ViewContext.put("parameter", parameter);
		return HtmlRestResult.html("/detail/file");
	}
		
	
	@RequestMapping("/selectSD")
	public BaseRestResult<String> upoa(HttpServletRequest request) {
		String[] cno = request.getParameterValues("ids");
		if (cno == null || cno.length == 0) {
			return BaseRestResult.warn("请选中sd账号");
		}
		if (cno.length != 1) {
			return BaseRestResult.warn("只能选中一个sd账户");
		}
		O2oLoanapplyEntity o2oLoanapplyUp = new O2oLoanapplyEntity();
		o2oLoanapplyUp.setCustomerNo(cno[0]);
		String s[] = cno[0].split(",");
		o2oLoanapplyUp.setCustomeRname(s[1]);
		ViewContext.put("loanApplySDEntity",o2oLoanapplyUp);
		HtmlRestResult.redirect("/sdViewServch?o2oLoanapplySd="+o2oLoanapplyUp);
		return HtmlRestResult.html("daliansd/view");
	}
	
	@RequestMapping(value = "/sdView")
	public BaseRestResult<String> sdView(O2oLoanapplyEntity o2oLoanapplySd) {
		ViewContext.put("loanApplySDEntity",o2oLoanapplySd);
		return HtmlRestResult.html("daliansd/view");
	}
	
	@RequestMapping(value = "/sdViewServch")
	public BaseRestResult<String> sdViewServch() {
		return HtmlRestResult.popHtmlFragment("daliansd/viewSearch");
	}
	
	/**
	 *  CXW 贷款详情显示证件号码等信息星号 http://tick.o2ojr.eascs.com/ticket/view/loan-12592
	 * @param houseId
	 * @return
	 */
	@RequestMapping("/view_bank_infocard")
	public BaseRestResult<String> view_address(String loanapplyNo) {
		O2oLoanapplyEntity loanapply=o2oloanapplyService.findById(loanapplyNo);
		ViewContext.put("loanapplyEntity", loanapply);
		return HtmlRestResult.popHtmlFragment("/detail/view_bankinfo");
	}
	
	/**
	 * 扣费按钮
	 * 
	 * @param loanapplyNo
	 * @return
	 */
	@RequestMapping("/fee_deduction")
	public BaseRestResult<String> fee_deduction(String loanapplyNo,String type) {
		logger.info("查询贷款保证金开始");
		LoanapplyExpand loanapplyExpand = loanapplyExpandService.queryLoanapplyNo(loanapplyNo);
		LoanapplyExpand expand = o2oChargeSituationService.queryExpandByLoanapplyNo(loanapplyNo);
		logger.info("查询贷款保证金信息:{}", expand);
		//type = "KF";// 扣费
		String message = o2oChargeSituationService.ChargingKFTF(expand, type);
		if ("SUCCESS".equals(message)){
			if("KF".equals(type)){
				return BaseRestResult.info("扣费成功");
			}else{
				return BaseRestResult.info("退费成功");
			}
		}
			
		else
			return BaseRestResult.warn(message);
		}
}
